from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
from django import forms
from web import models
from web.utils.bootstrip import BootstrapModelForm


class UserModelForm(BootstrapModelForm):
    name = forms.CharField(min_length=2, label="用户名")

    class Meta:
        model = models.UserInfo
        fields = ["name", "password", "age", "account", "create_time", "gender", "depart"]


class PrettyModelForm(BootstrapModelForm):
    mobile = forms.CharField(
        label="手机号",
        validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误')]
    )

    class Meta:
        model = models.PrettyNum
        fields = ["mobile", "price", "level", "status"]

    def clean_mobile(self):
        # 获取用户输入的内容
        txt_mobile = self.cleaned_data["mobile"]
        exists = models.PrettyNum.objects.filter(mobile=txt_mobile).exists()
        if exists:
            raise ValidationError("钩子方法实现判断手机号码已存在")
        # 验证通过，返回用户输入的数据
        return txt_mobile


class PrettyEditModelForm(BootstrapModelForm):
    # 重新定义字段，让其不可修改
    # mobile = forms.CharField(disabled=True, label="手机号")
    mobile = forms.CharField(
        label="手机号",
        validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误')]
    )

    class Meta:
        model = models.PrettyNum
        fields = ["mobile", "price", "level", "status"]

    def clean_mobile(self):
        # 获取当前编辑行数据的id [self.instance.pk]
        # 获取用户输入的内容
        txt_mobile = self.cleaned_data["mobile"]
        # 排除自身以外的手机号是否已存在
        exists = models.PrettyNum.objects.exclude(id=self.instance.pk).filter(mobile=txt_mobile).exists()
        if exists:
            raise ValidationError("手机号码已存在")
        # 验证通过，返回用户输入的数据
        return txt_mobile
